﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using BMS.Syncro.Devices.Configuration.Entities;
using BMS.Syncro.Devices.Configuration.Interfaces;

namespace BMS.Syncro.Devices.Configuration
{
    public class XmlConfiguration : IConfiguration
    {
        #region Properties
        private List<DeviceConfigurationEntity> _configurations;
        #endregion Properties

        #region IConfiguration Members

        public List<DeviceConfigurationEntity> Configurations
        {
            get
            {
                if (_configurations == null)
                    this.LoadConfigurations();
                return _configurations;
            }

            set
            {
                _configurations = value;
            }
        }

        public void LoadConfigurations()
        {
            string configurationFilePath = @".\SynchroDeviceConfigurations.xml";
            var deviceConfigurationList = new List<DeviceConfigurationEntity>();

            if (File.Exists(configurationFilePath))
            {
                var tTypes = new XmlDocument();
                tTypes.Load(configurationFilePath);

                XmlNodeList syncroDeviceConfigurationsNode = tTypes.GetElementsByTagName("SynchroDeviceConfigurations");
                XmlNodeList ftpUploaderConfigurationNodes = ((XmlElement)syncroDeviceConfigurationsNode[0]).GetElementsByTagName("Device");

                foreach (XmlElement configurationNode in ftpUploaderConfigurationNodes)
                {
                    var deviceConfiguration = new DeviceConfigurationEntity();
                    XmlNodeList directoryInfo = configurationNode.GetElementsByTagName("Add");
                    deviceConfiguration.Ip = ((XmlElement)directoryInfo[0]).GetAttribute("Ip");
                    deviceConfiguration.Port = ((XmlElement)directoryInfo[0]).GetAttribute("Port");
                    deviceConfiguration.Name = ((XmlElement)directoryInfo[0]).GetAttribute("Name");
                    deviceConfiguration.Observations = ((XmlElement)directoryInfo[0]).GetAttribute("Observations");
                    deviceConfigurationList.Add(deviceConfiguration);
                }
            }
            else
                throw new ApplicationException("El archivo " + configurationFilePath + " utilizado para cargar las configuraciones de dispositivos no existe.");

            _configurations = (List<DeviceConfigurationEntity>)deviceConfigurationList;
        }

        public List<DeviceConfigurationEntity> GetConfigurations()
        {
            return _configurations;
        }

        #endregion
       
    }
}
